/**
 * SEVAS - Swiss Electronic Vaccination Advisor Service / Agile Development
 *
 * $Id: Controller.java 34 2010-08-19 20:15:52Z zimmr7@bfh.ch $
 */
package ch.bfh.sevas;

import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.PersistenceException;
import javax.persistence.TypedQuery;

public class Controller {

    private EntityManagerFactory emf = null;

    public Controller() {
        emf = Persistence.createEntityManagerFactory("./data/sevas.odb");
    }

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Patient patient) {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            em.persist(patient);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Patient patient) throws Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            patient = em.merge(patient);
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Long id = patient.getId();
                if (findPatient(id) == null) {
                    throw new Exception("The patient with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Long id) throws Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Patient patient;
            try {
                patient = em.getReference(Patient.class, id);
                patient.getId();
            } catch (EntityNotFoundException enfe) {
                throw new Exception("The patient with id " + id + " no longer exists.", enfe);
            }
            em.remove(patient);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Patient> findAllPatients() {
        EntityManager em = getEntityManager();
        try {
            TypedQuery<Patient> q = em.createQuery("select p from Patient p", Patient.class);
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Patient findPatient(Long id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Patient.class, id);
        } finally {
            em.close();
        }
    }

    public Patient findPatient(String term) {
        EntityManager em = getEntityManager();
        try {
            TypedQuery<Patient> q = em.createQuery("select p from Patient p where p.surname like '%:term%' or p.givenName like '%:term%'", Patient.class);
            return q.setParameter("term", term).getSingleResult();

        } finally {
            em.close();
        }
    }
    public int getPatientCount() {
        EntityManager em = getEntityManager();
        try {
            Query q = em.createQuery("select count(p) from Patient p");
            return ((Long) q.getSingleResult()).intValue();
        } catch (PersistenceException e) {
            return 0; // TODO check "Type Patient is not found (error 301)"
        } finally {
            em.close();
        }
    }

    void cleanup() {
        if (emf != null) {
            emf.close();
        }
    }
}
